import 'dart:ui';

import 'package:flutter/material.dart';
import 'dart:ui' as ui;

import 'package:flutter_book/constant/color.dart';
import 'package:flutter_book/page/book/animation_util/data/text_page_model.dart';
import 'package:get/get.dart';

class PagePainter extends CustomPainter {
  final TextPage page;
  final TextStyle style;
  final TextStyle? titleStyle;
  final int pageIndex;
  final bool debug;

  PagePainter(this.pageIndex, this.page, this.style, this.titleStyle, [this.debug = false]);

  final Paint alertBgPaint = Paint() // 创建一个画笔并配置其属性
    ..strokeWidth = 10 // 画笔的宽度
    ..isAntiAlias = true // 是否抗锯齿
    ..color = AppColor.white // 画笔颜色
    ..style = PaintingStyle.fill; //是否填充

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawPath(
        Path()
          ..moveTo(0, 0)
          ..lineTo(Get.width, 0)
          ..lineTo(Get.width, Get.height)
          ..lineTo(0, Get.height)
          ..lineTo(0, 0)
          ..close(),
        alertBgPaint);

    if (debug) print("****** [TextComposition paint start] [${DateTime.now()}] ******");
    final lineCount = page.lines.length;
    final tp = TextPainter(textDirection: TextDirection.ltr, maxLines: 1);
    for (var i = 0; i < lineCount; i++) {
      final line = page.lines[i];
      if (line.letterSpacing != null && (line.letterSpacing! < -0.1 || line.letterSpacing! > 0.1)) {
        tp.text = TextSpan(
          text: line.text,
          style: line.isTitle
              ? titleStyle?.copyWith(letterSpacing: line.letterSpacing)
              : style.copyWith(letterSpacing: line.letterSpacing),
        );
      } else {
        tp.text = TextSpan(text: line.text, style: line.isTitle ? titleStyle : style);
      }
      final offset = Offset(line.dx, line.dy);
      if (debug) print("$offset ${line.text}");
      tp.layout();

      tp.paint(canvas, offset);
    }

    if (debug) print("****** [TextComposition paint end  ] [${DateTime.now()}] ******");
  }

  @override
  bool shouldRepaint(PagePainter old) {
    print("shouldRepaint");
    return old.pageIndex != pageIndex;
  }
}
